import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_09_game/base/refresh/base_refresh.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/pages/game/game_detail/game_detail_logic.dart';
import 'package:flutter_09_game/pages/game/game_detail/game_detail_page/game_detail_page_logic.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/utils/extensions/num_ext.dart';
import 'package:flutter_09_game/utils/sound/sound_manager.dart';
import 'package:flutter_09_game/utils/utils_other.dart';
import 'package:flutter_09_game/widgets/btn_dropdown.dart';
import 'package:flutter_09_game/widgets/button/common_button.dart';
import 'package:flutter_09_game/widgets/image/auto_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

class WidgetBetOperation extends StatelessWidget {
  const WidgetBetOperation(
      {super.key, required this.gameLogic, required this.logic});

  final GameDetailPageLogic logic;

  final GameDetailLogic gameLogic;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        _buildBetOptions(),
        6.verticalSpaceFromWidth,
        _buildInputBet(),
        12.verticalSpaceFromWidth,
        Obx(() {
          return CommonButton.expend(
            title: LocaleKeys.ok.tr,
            enable: logic.canPlaceBetRx.value &&
                gameLogic.proShowBetRx.value == false,
            alwaysCanClick: true,
            onClick: () {
              logic.postGameRoundJoin();
            },
          );
        })
      ],
    );
  }

  /// 构建投注选项区域
  Widget _buildBetOptions() {
    return Container(
        height: 90.w,
        decoration: BoxDecoration(
          // color: Colors.black.withOpacity(0.3), // 半透明黑色背景
          borderRadius: BorderRadius.circular(1000.w), // 完全圆角
        ),
        padding: EdgeInsets.symmetric(horizontal: 12.w),
        child: Obx(() {
          return Row(
            children: [
              // 左侧"单"选项
              Expanded(
                child: _buildBetOption(
                    title: LocaleKeys.single.tr,
                    totalBet: gameLogic.leftBetOptionRx.value?.amount
                            .formatLimiting() ??
                        '0',
                    isLeft: true,
                    onClick: () {
                      if (gameLogic.soundRx.value) {
                        SoundManager().playButtonSound();
                      }
                      logic.selectOddRx.value = false;
                    }),
              ),
              // 右侧"双"选项
              Expanded(
                child: _buildBetOption(
                    title: LocaleKeys.double.tr,
                    totalBet: gameLogic.rightBetOptionRx.value?.amount
                            .formatLimiting() ??
                        '0',
                    isLeft: false,
                    onClick: () {
                      if (gameLogic.soundRx.value) {
                        SoundManager().playButtonSound();
                      }
                      logic.selectOddRx.value = true;
                    }),
              ),
            ],
          );
        }));
  }

  List<Color> getBetOptionColors(bool isLeft) {
    if (isLeft && logic.selectOddRx.value == false) {
      return [
        AppColor.homePrizePoolIndicator.withOpacity(0.3), // 绿色渐变
        AppColor.pageBgColor.withOpacity(0),
      ];
    } else if (isLeft == false && logic.selectOddRx.value == true) {
      return [
        AppColor.gameResultEven.withOpacity(0.3), // 红色渐变
        AppColor.pageBgColor.withOpacity(0),
      ];
    }
    return [
      Colors.black.withOpacity(0.3), // 红色渐变
      Colors.black.withOpacity(0.3),
    ];
  }

  Color getBorderSide(bool isLeft) {
    if (isLeft && logic.selectOddRx.value == false) {
      return AppColor.homePrizePoolIndicator;
    } else if (isLeft == false && logic.selectOddRx.value == true) {
      return AppColor.gameResultEven;
    }
    return Colors.black;
  }

  /// 构建单个投注选项
  Widget _buildBetOption(
      {required String title,
      required String totalBet,
      required bool isLeft,
      required Function onClick}) {
    return GestureDetector(
      onTap: () {
        onClick.call();
      },
      child: Container(
        height: 90.w,
        decoration: BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: getBetOptionColors(isLeft)),
          borderRadius: BorderRadius.only(
            topLeft: isLeft ? Radius.circular(1000.w) : Radius.zero,
            bottomLeft: isLeft ? Radius.circular(1000.w) : Radius.zero,
            topRight: !isLeft ? Radius.circular(1000.w) : Radius.zero,
            bottomRight: !isLeft ? Radius.circular(1000.w) : Radius.zero,
          ),
          border: Border(
              top: BorderSide(
            color: getBorderSide(isLeft),
            width: 1.w,
          )),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            // 选项标题
            Padding(
              padding: EdgeInsets.only(top: 8.w),
              child: Text(
                title,
                style: TextStyle(
                  fontSize: 24.sp,
                  fontWeight: FontWeight.w600,
                  color: isLeft
                      ? AppColor.textPrimary.withOpacity(0.3) // 灰色30%透明度
                      : AppColor.gameResultEven, // 红色
                ),
              ),
            ),
            // 总下注信息
            Padding(
              padding: EdgeInsets.only(bottom: 8.w),
              child: _buildTotalBetInfo(totalBet),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildInputBet() {
    return Container(
      // margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 6.w)
          .copyWith(bottom: 4.w),
      decoration: BoxDecoration(
        color: Colors.black.withOpacity(0.3),
        borderRadius: BorderRadius.circular(8.w),
      ),
      child: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: TextField(
                  controller: logic.amountController,
                  // focusNode: _focusNode,
                  // obscureText: widget.isPassword ? _obscureText : false,
                  // autofocus: widget.autofocus,
                  // enabled: widget.enabled,
                  keyboardType: TextInputType.number,
                  // textInputAction: widget.textInputAction,
                  inputFormatters: [
                    FilteringTextInputFormatter.digitsOnly,
                    LengthLimitingTextInputFormatter(10),
                  ],

                  onChanged: (text) {},

                  // textAlignVertical: TextAlignVertical.,
                  // 文本垂直居中
                  // cursorColor: widget.cursorColor ?? AppColor.primary,
                  style: TextStyle(
                    fontSize: 14.sp,
                    fontWeight: FontWeight.w500,
                    color: AppColor.textPrimary.withOpacity(0.94),
                  ),
                  decoration: InputDecoration(
                    border: InputBorder.none,
                    enabledBorder: InputBorder.none,
                    focusedBorder: InputBorder.none,
                    disabledBorder: InputBorder.none,
                    errorBorder: InputBorder.none,
                    focusedErrorBorder: InputBorder.none,
                    counterText: '',
                    hintText: LocaleKeys.lotteryEnterAmount.tr,
                    isDense: true,
                    isCollapsed: true,
                    // 紧凑布局，有助于垂直对齐
                    hintStyle: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w400,
                      color: AppColor.textPrimary.withOpacity(0.5),
                    ),
                    // contentPadding: EdgeInsets.only(bottom: 2.w), // 调整内边距
                  ),
                ),
              ),
              8.horizontalSpace,
              GestureDetector(
                onTap: () {
                  logic.showBetSetting();
                  // logic.amountController.text = '';
                },
                child: AutoImage(
                  Assets.commonGameBetSetting,
                  width: 32.w,
                ),
              ),
              8.horizontalSpace,
              GestureDetector(
                onTap: () {
                  logic.amountController.text = '';
                },
                child: AutoImage(
                  Assets.commonGameClear,
                  width: 32.w,
                ),
              ),
              8.horizontalSpace,
              Obx(() {
                return _buildTopDropdown(logic.symbols,
                    value: AppUserManager().currentWalletRx.value.symbol ?? '',
                    onChanged: (value) {
                  if (gameLogic.soundRx.value) {
                    SoundManager().playButtonSound();
                  }
                  AppUserManager().selectUserWallet(value);
                });
              })
            ],
          ),
          6.verticalSpaceFromWidth,
          Obx(() {
            return SizedBox(
              width: double.infinity,
              child: Wrap(
                runSpacing: 4.w,
                spacing: 4.w,
                alignment: WrapAlignment.start,
                // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: logic.quickBetRowsRx.asMap().entries.map((entry) {
                  final index = entry.key;
                  final value = entry.value;
                  final isSelected =
                      logic.selectedQuickBetIndexRx.value == index;

                  return CommonButton(
                    // title: ,
                    title: ((value.amount ?? 0) ~/ 1000000).toString(),
                    onClick: () {
                      logic.selectQuickBet(index, value.amount ?? 0);
                      if (gameLogic.soundRx.value) {
                        SoundManager().playButtonSound();
                      }
                    },
                    width: 62.w,
                    height: 32.w,
                    enable: isSelected,
                    alwaysCanClick: true,
                    fontSize: 12.sp,
                  );
                }).toList(),
              ),
            );
          })
        ],
      ),
    );
  }

  Widget _buildTopDropdown(
    List<String> items, {
    required String value,
    required Function(String) onChanged,
  }) {
    return BtnDropdown(
        items: items,
        value: value,
        width: 100.w,
        onChanged: (value) {
          onChanged.call(value);
        },
        child: Container(
          width: 93.w,
          height: 32.w,
          padding: EdgeInsets.symmetric(horizontal: 4.w),
          decoration: BoxDecoration(
              color: AppColor.textPrimary.withOpacity(0.15),
              borderRadius: BorderRadius.circular(8.w)),
          child: Row(
            children: [
              AutoImage(
                UtilsOther().getAmountTagIcon(value),
                width: 20.w,
              ),
              4.horizontalSpace,
              Expanded(
                  child: Text(
                value,
                textAlign: TextAlign.start,
                style: TextStyle(
                  fontSize: 12.sp,
                  // fontWeight: FontWeight.w900,
                  color: AppColor.textPrimary.withOpacity(0.7),
                ),
              )),
              AutoImage(
                Assets.promotionCommissionCaretDown,
                width: 16.w,
                color: AppColor.textPrimary.withOpacity(0.7),
              )
            ],
          ),
        ));
  }

  /// 构建总下注信息
  Widget _buildTotalBetInfo(String amount) {
    return Container(
      // height: 28.w,
      width: 110.w,
      padding: EdgeInsets.all(8.w),
      decoration: BoxDecoration(
        color: AppColor.pageBgColor, // 深色背景
        borderRadius: BorderRadius.circular(100.w), // 完全圆角
      ),
      child: Row(
        // mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            LocaleKeys.betTotal.tr,
            style: TextStyle(
              fontSize: 10.sp,
              fontWeight: FontWeight.w400,
              color: AppColor.textPrimary.withOpacity(0.7),
            ),
          ).marginOnly(right: 8.w),
          // 8.horizontalSpace,
          Text(
            amount,
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w600,
              color: AppColor.textPrimary.withOpacity(0.94),
            ),
          ),
        ],
      ),
    );
  }
}
